package com.invest.repository;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.invest.domain.dao.SystemUserDAO;
import com.invest.domain.dao.SystemUserRolesDAO;
import com.invest.domain.model.SystemUserDO;
import com.invest.domain.model.SystemUserDOExample;
import com.invest.domain.model.SystemUserRolesDO;
import com.invest.domain.model.SystemUserRolesDOExample;
import com.invest.infra.mvc.utils.PageVO;
import com.invest.utils.security.PasswordUtils;
import com.invest.vo.UserHolder;
import com.invest.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Date;
import java.util.List;

/**
 * Created by evan on 2016/6/11.
 */
@Repository
public class SysUserRepository {
    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private  SystemUserDAO systemUserDAO;

    @Autowired
    private SystemUserRolesDAO systemUserRolesDAO;

    public void save(final UserVO userVO,final SystemUserDO operator){

        final SystemUserDO systemUserDO = userVO.populate(true, operator.getId());
        //加密密码
        systemUserDO.setPassword(PasswordUtils.md5Pwd(systemUserDO.getId(),systemUserDO.getPassword()));

        final List<SystemUserRolesDO> systemUserRolesDOs = userVO.populateRoles(true, operator.getId());

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {

                systemUserDAO.insertSelective(systemUserDO);
                for(SystemUserRolesDO rolesDO : systemUserRolesDOs) {
                    systemUserRolesDAO.insertSelective(rolesDO);
                }
            }
        });

    }

    public void delete(final String id){

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                SystemUserRolesDOExample example = new SystemUserRolesDOExample();
                example.createCriteria().andUserIdEqualTo(id);
                systemUserRolesDAO.deleteByExample(example);
                systemUserDAO.deleteByPrimaryKey(id);
            }
        });
    }

    public boolean changePwd(String userId,String pwd,String operator){

        SystemUserDO admin = new SystemUserDO();
        admin.setId(userId);
        admin.setUpdateTime(new Date());
        admin.setUpdateUser(operator);
        admin.setPassword(PasswordUtils.md5Pwd(userId,pwd));
        return systemUserDAO.updateByPrimaryKeySelective(admin) == 1;
    }

    public UserHolder loadUser(String adminId, boolean withRoles){

        UserHolder userHolder = new UserHolder();

        //基本
        SystemUserDO userDO = systemUserDAO.selectByPrimaryKey(adminId);
        if(userDO == null){
            throw new UsernameNotFoundException(adminId+"不存在");
        }
        userHolder.setSystemUserDO(userDO);


        //角色
        if(withRoles) {
            List<SystemUserRolesDO> roles = queryByAdmin(adminId);
            userHolder.setSystemUserRolesDOList(roles);
        }
        return userHolder;
    }

    public List<SystemUserRolesDO> queryByAdmin(String adminId){
        SystemUserRolesDOExample example = new SystemUserRolesDOExample();
        example.createCriteria().andUserIdEqualTo(adminId);
        return  systemUserRolesDAO.selectByExample(example);
    }


    public Page<SystemUserDO> query(SystemUserDO user, PageVO pageVO){

        Page<SystemUserDO> page = PageHelper.startPage(pageVO.getPageNum(), pageVO.getPageSize(), pageVO.getOrder());
        SystemUserDOExample example = new SystemUserDOExample();
        SystemUserDOExample.Criteria criteria = example.createCriteria();


        if(StringUtils.isNotBlank(user.getId())) {
            criteria.andIdEqualTo(user.getId());
        }

        if(StringUtils.isNotBlank(user.getName())) {
            criteria.andNameLike("%"+user.getName()+"%");
        }

        if(StringUtils.isNotBlank(user.getStatus())) {
            criteria.andStatusEqualTo(user.getStatus());
        }
        systemUserDAO.selectByExample(example);
        return page;
    }
}
